﻿using CodeGeneratorBootstrap.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeGeneratorBootstrap.Util;

namespace CodeGeneratorBootstrap.Template.Web.Views
{
    public partial class ViewDetail : ITemplate
    {
        public MetaData Data { get; set; }
        public List<LookupClassModel> lookups { get; set; }
        public List<PickupListModel> pickuplist { get; set; }

        public string parent_attr_PK_name = "";
        public string parent_attr_Name_name = "";

        public string parent_class_name = "";


        public string Filename
        {
            get { return "Edit{ClassName}.cshtml"; }
        }
        public string FolderName
        {
            get { return ""; }
        }

        public bool IsGenerateOneTime { get { return false; } }
        public bool IsGenerateFolder { get { return true; } }
        public bool IsRequiredOnlyOneMember { get { return true; } }
        public GenerateStyle GenerateStyle { get { return GenerateStyle.Normal; } }


        public bool IsChildClass()
        {
            if (Data.Models[0].ParentClass != null && Data.Models[0].ParentClass.Count > 0)
            {
                parent_class_name = Data.Models[0].ParentClass[0].Name;

                foreach (var attr in Data.Models[0].ParentClass[0]._attributes)
                {
                    if (attr.Pk)
                        parent_attr_PK_name = attr.Name;
                }
                return true;
            }
            else
                return false;
        }
        public String GetPKOfLookup(List<LookupModel> list)
        {
            foreach (LookupModel l in list)
            {
                if (l.DestAttribute.Pk)
                    return l.DestAttribute.Name;
            }
            return "";
        }

        public String GetNameOfLookup(List<LookupModel> list)
        {
            foreach (LookupModel l in list)
            {
                if (!l.DestAttribute.Pk)
                    return l.DestAttribute.Name;
            }
            return "";
        }



        public bool IsParentClass()
        {

            foreach (var attr in Data.Models[0]._attributes)
            {
                if (attr.DataType.Name == "Master Detail") {
                    return true;
                }  
            }
            return false;
        }

        //Calculation Field
        public string IsCalculateOperandReturnFnName(string currentAtt)
        {
            ClassModel Clsmodel = Data.Models[0];
            int a = Clsmodel.Id;
            List<AttributeModel> att = Clsmodel._attributes.FindAll(x => x.FieldType.Name.Equals("Calculation Field"));
            List<string> functions = new List<string>();
            if (att != null)
            {
                foreach (AttributeModel item in att)
                {
                    string[] separators = { "+", "-", "*", "/", "^", "(", ")", " ", ".concat", ".substr", ".contain", "AddDate", "AddMonth", "AddYear", "Minimum", "Maximum", "[", "]", "DateDiff", ",", "MinDate", "MaxDate", "Summary" }; 
                    string[] words = item.Formula.Split(separators, StringSplitOptions.RemoveEmptyEntries);

                    if (words.Contains(currentAtt))
                    {
                        functions.Add(string.Concat("Calculation", Clsmodel.Name, "_", item.Name, "();")); //function name
                    }
                }
                return string.Join(" ", functions);
            }
            return "";
        }

        /// <summary>
        /// Name : Phuwadet Boonpho
        /// Date : 19/04/2014
        /// Description : ตรวจสอบว่ามี Attribute ที่เป็น Image ใน Class หรือไม่ ถ้ามีต้องสามารถ Upload ได้
        /// </summary>
        /// <param name="model"></param>
        /// <returns>String</returns>
        public string IsFormUpload()
        {
            ClassModel Clsmodel = Data.Models[0];
            List<AttributeModel> list = new List<AttributeModel>();

            foreach (AttributeModel c in Clsmodel._attributes)
            {
                if (c.FieldType.Name == "Image")
                {
                    return ", enctype = \"multipart/form-data\"";
                }
            }

            return "";
        }

        /// <summary>
        /// Name ::: Mr. Akawit Tangkupatanonth
        /// Date ::: 16/03/2014
        /// Description ::: This function for check this class use multi-validate in attribute at least one
        /// </summary>
        /// <returns>Boolean</returns>

        public bool CheckUseMultiValidateInAttribute(ClassModel model)
        {
            List<AttributeModel> list = new List<AttributeModel>();
            foreach (AttributeModel c in model._attributes)
            {
                if (c.Validate)
                {
                    if (c.ValidateFormula.Contains("Disable("))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Name : Phuwadet Boonpho
        /// Date : 12/05/2014
        /// Description : ตรวจสอบว่ามี Attribute ที่เป็น Image ใน Class หรือไม่
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Boolean</returns>
        public bool CheckFieldTypeImage(ClassModel model)
        {
            List<AttributeModel> list = new List<AttributeModel>();
            foreach (AttributeModel c in model._attributes)
            {
                if (c.FieldType.Name == "Image")
                {
                    return true;
                }
            }
            return false;
        }

        public string ResultAttribute(ClassModel model)
        {
            string result = "";
            foreach (AttributeModel c in model._attributes.Where(a => a.FieldType.Name.Equals("Image")).ToList())
            {
                if (result != "")
                {
                    result += ",";
                }
                result += "\""+c.Name+"\"" ;
            }
            return result;
        }



		/// <summary>
		/// Create by: Nathawat (11-05-2014)
		/// provide method for check Class has GeoLocation attribute
		/// </summary>
		/// <param name="model">Class Model</param>
		/// <returns>bool</returns>
		public bool HasGeoLocationAttribute(ClassModel model)
		{
			foreach (AttributeModel attribute in model._attributes)
			{
				if (attribute.DataType.Name.Equals("GeoLocation"))
				{
					return true;
				}
			}
			return false;
		}

        //[ding Start]
        public List<LayoutSectionModel> getListLayoutSection()
        {
            ClassModel classModel = Data.Models[0];

            List<LayoutSectionModel> result = new List<LayoutSectionModel>();

            result = classModel.LayoutSection.OrderBy(item => item.SeqNo).ToList();

            if (!classModel.LayoutSection.Any(cls => cls.Id.Equals(null)))
            {
                result.Add(new LayoutSectionModel()
                {
                    Id = null,
                    LayoutColumn = 2,
                    SectionName = "Information",
                    SeqNo = 0,
                    Width = 100,
                    Height = 100,
                    ShowScrollbars = 0,
                    ShowLabel = 1,
                    TabkeyOrder = 1

                });
            }

            return result;
        }

        public string showScrollbars(LayoutSectionModel listLayoutSection)
        {
            string result = "";

            if (listLayoutSection.ShowScrollbars == 1)
            {
                result = "overflow: scroll;";
                if ((listLayoutSection.Width != -1) && (listLayoutSection.Height != -1))
                {
                    result += "width:" + listLayoutSection.Width + "px; height:" + listLayoutSection.Height + "px;";
                }
                else if ((listLayoutSection.Width != -1) && (listLayoutSection.Height == -1))
                {
                    result += "width:" + listLayoutSection.Width + "px;";
                }
                else if ((listLayoutSection.Width == -1) && (listLayoutSection.Height != -1))
                {
                    result += "height:" + listLayoutSection.Height + "px;";
                }
                else
                {
                    result += "width:auto;height:auto; ";
                }
            }
            else
            {
                result = "width:auto;height:auto; ";
            }

            return result;
        }

        public List<ListObjectMasterDetailFilter> ListMasterDetailFilter()
        {
            ClassModel classModel = Data.Models[0];

            List<AttributeModel> list = new List<AttributeModel>();
            List<ListObjectMasterDetailFilter> listMS = null;

            ClassServices.CodeGenBLClient CS = new ClassServices.CodeGenBLClient();

            list = classModel.GetAttributes().Where(a => a.DataType.Name.Equals("Master Detail")).ToList();

            if (list.Count > 0)
            {
                listMS = new List<ListObjectMasterDetailFilter>();

                foreach (var attribute in list)
                {
                    var DestClass = CS.GetClass(new ClassServices.ClassPkDto { ClassId = attribute.ChildClass.Id });
                    var filters = CS.GetMasterDetailFilter(new ClassServices.FilterPkDto { AttributeId = attribute.Id });

                    if (filters.Data != null)
                    {
                        for (int i = 0; i < filters.Data.Count; i++)
                        {
                            listMS.Add(new ListObjectMasterDetailFilter
                            {
                                Name = filters.Data[i].Name,
                                NameID = filters.Data[i].Name + "_ID" + filters.Data[i].Id,
                                Formula = SplitFormulaMasterDetailFilter(filters.Data[i].Formula, new ClassModel(DestClass.Data)),
                                AttributeMasterDetailName = attribute.Name,
                                ChildClassName = attribute.ChildClass.Name,
                                ID = filters.Data[i].Id,
                                FilterNameModel = "Filter" + filters.Data[i].Name
                            });
                        }
                    }
                }
            }

            return listMS;
        }

        public string SplitFormulaMasterDetailFilter(string formula, ClassModel DestClass)
        {

            string StrFormula = formula;
            string StrAttribute = string.Empty;
            string StrOperator = string.Empty;
            string StrValue = string.Empty;
            string[] splitWord = null;
            string[] splitformula = null;
            string splitAttr = null;
            int AttributeID = 0;
            string StrTotal = string.Empty;

            AttributeModel ListName = null;

            splitWord = StrFormula.Split(new string[] { "&&", "||" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < splitWord.Length; i++)
            {
                splitformula = splitWord[i].Split(new string[] { "==", ">=", "<=", "!=", "<", ">", "begin with", "end with", "contains with" }, 2, StringSplitOptions.RemoveEmptyEntries);
                splitAttr = splitWord[i].Trim();
                StrAttribute = splitformula[0].Trim();

                if (splitAttr.IndexOf("==") > -1)
                {
                    StrOperator = "==";
                }
                else if (splitAttr.IndexOf(">=") > -1)
                {
                    StrOperator = ">=";
                }
                else if (splitAttr.IndexOf("<=") > -1)
                {
                    StrOperator = "<=";
                }
                else if (splitAttr.IndexOf("!=") > -1)
                {
                    StrOperator = "!=";
                }
                else if (splitAttr.IndexOf("<") > -1)
                {
                    StrOperator = "<";
                }
                else if (splitAttr.IndexOf(">") > -1)
                {
                    StrOperator = ">";
                }
                else if (splitAttr.ToLower().IndexOf("begin with") > -1)
                {
                    StrOperator = "startswith";
                }
                else if (splitAttr.ToLower().IndexOf("end with") > -1)
                {
                    StrOperator = "endswith";
                }
                else if (splitAttr.ToLower().IndexOf("contains with") > -1)
                {
                    StrOperator = "contains";
                }

                AttributeID = Convert.ToInt32(StrAttribute);
                ListName = DestClass._attributes.Where(attr => attr.Id.Equals(AttributeID)).FirstOrDefault();

                if (DataTypeMapper.ForModels(ListName).ToLower() == "string")
                {

                    if (splitformula[1].Trim() == string.Empty)
                    {
                        StrValue = "\"\"";

                    }
                    else if (splitformula[1].Trim() == null)
                    {
                        StrValue = null;
                    }
                    else
                    {
                        StrValue = splitformula[1].Trim().Replace("\"", "\\\"");
                        StrValue = "\"" + StrValue + "\"";
                    }

                }
                else
                {
                    StrValue = splitformula[1].Trim();
                }


                if (DataTypeMapper.ForModels(ListName).ToLower() == "string")
                {
                    if ((StrOperator == "!=") || (StrOperator == "==") || (StrOperator == ">") || (StrOperator == "<") || (StrOperator == ">=") || (StrOperator == "<="))
                    {
                        StrTotal = ListName.Name + ".CompareTo(" + StrValue + ")" + StrOperator + "0";
                    }
                    else if (StrOperator.ToLower() == "contains")
                    {
                        StrTotal = ListName.Name + ".Contains(" + StrValue + ")";
                    }
                    else if (StrOperator.ToLower() == "startswith")
                    {
                        StrTotal = ListName.Name + ".StartsWith(" + StrValue + ")";
                    }
                    else if (StrOperator.ToLower() == "endswith")
                    {
                        StrTotal = ListName.Name + ".EndsWith(" + StrValue + ")";
                    }
                }
                else if ((DataTypeMapper.ForModels(ListName).ToLower() == "datetime") || (DataTypeMapper.ForModels(ListName).ToLower() == "datetime?"))
                {

                    StrTotal = ListName.Name + StrOperator + " DateTime.ParseExact(\"" + StrValue + "\", \"yyyy-MM-dd\", new System.Globalization.CultureInfo(\"en-US\"))";

                }
                else
                {

                    StrTotal = ListName.Name + StrOperator + StrValue;
                }
                StrFormula = StrFormula.Replace(splitAttr, " a." + StrTotal + " ");
            }

            StrFormula = "Where(a => " + StrFormula + " ).ToList();";

            return StrFormula;
        }

        public class ListObjectMasterDetailFilter
        {
            public string Name;
            public string NameID;
            public string Formula;
            public string AttributeMasterDetailName;
            public string ChildClassName;
            public string FilterNameModel;
            public int ID;
        }

        //[Ding end]

        // check for multipleSelected 
        public bool HasMultipleSeletedAttribute(ClassModel model)
        {
            foreach (AttributeModel attribute in model._attributes)
            {
                if (attribute.DataType.Name.Equals("MultipleSelected"))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
